import 'package:containerbox_study/toutiao_mock_data.dart';
import 'package:flutter/material.dart';

import '../../Toutiao/toutiao_articleItem.dart';

import 'package:flutter_easyrefresh/easy_refresh.dart';


class TouTiaoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ToutiaoPageState();
}

class _ToutiaoPageState extends State<TouTiaoPage> {
  List<Map<String, Object>> _listItems = [];
  int _currentPage = 1;

  EasyRefreshController _refreshController = EasyRefreshController();

  @override
  void initState() {
    super.initState();

    EasyRefresh.defaultHeader = ClassicalHeader(
      refreshText: '下拉即将刷新',
      refreshReadyText: '正在下拉',
      refreshedText: '刷新完成',
      refreshingText: '正在请求数据中...',
      refreshFailedText: '请求失败,请检查网络',
      infoText: '更新时间 xxxx : xxx',
    );

    EasyRefresh.defaultFooter = ClassicalFooter(
        loadText: '上拉加载更多',
        loadReadyText: '正在上拉',
        loadedText: '加载完成',
        loadingText: '正在请求数据中',
        loadFailedText: '加载失败,请检查网络...',
        noMoreText: '没有更多数据...');

    _requestToutiaoDataItems();
  }

  void _refresh() async {
    _currentPage = 1;
    _requestToutiaoDataItems();
  }

  void _load() async {
    _currentPage += 1;
    _requestToutiaoDataItems();
  }

  void _requestToutiaoDataItems() async {
    List<Map<String, Object>> _newItems =
        await ToutiaoData.list(_currentPage, 20);
    this.setState(() {
      if (_currentPage == 1) {
        _listItems = _newItems;
      } else {
        _listItems += _newItems;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
      child:EasyRefresh(
      controller: _refreshController,
      onLoad: () async {
        _load();
      },
      onRefresh: () async {
        _refresh();
      },
      child: ListView.builder(

        itemBuilder: (BuildContext context, int index) {
          return articleItem(
            _listItems[index]['title'].toString(),
            _listItems[index]['imageUrl'].toString(),
            _listItems[index]['viewCount'] as int,
            index,
          );
        },
        itemCount: _listItems.length,
        itemExtent: 120,
      ),
      )
    ),    
    );
  }
}
